package coreservlets.ch9;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShowSession extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String ACCESS_COUNT_SESSION_KEY = "accesscount";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		HttpSession session = req.getSession();
		String heading;
		Integer accessCount = (Integer) session
				.getAttribute(ACCESS_COUNT_SESSION_KEY);
		if (accessCount == null) {
			accessCount = new Integer(0);
			heading = "welcome newcomer";
		} else {
			heading = "welcome back";
			accessCount = new Integer(accessCount.intValue() + 1);
		}
		session.setAttribute(ACCESS_COUNT_SESSION_KEY, accessCount);
		PrintWriter out = resp.getWriter();
		String title = "Session Tracking Example";
		String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">\n";
		out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title
				+ "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n"
				+ "<CENTER>\n" + "<H1>" + heading + "</H1>\n"
				+ "<H2>Information on Your Session:</H2>\n"
				+ "<TABLE BORDER=1>\n" + "<TR BGCOLOR=\"#FFAD00\">\n"
				+ " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n"
				+ " <TD>" + session.getId() + "\n" + "<TR>\n"
				+ " <TD>Creation Time\n" + " <TD>"
				+ new Date(session.getCreationTime()) + "\n" + "<TR>\n"
				+ " <TD>Time of Last Access\n" + " <TD>"
				+ new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n"
				+ " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount
				+ "\n" + "</TABLE>\n" + "</CENTER></BODY></HTML>");
	}
}
